package org.shreker.shan.website.business.listener;

import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.Map;
import org.shreker.shan.rbac.annotation.PermissionRequired;
import org.shreker.shan.rbac.domain.Permission;
import org.shreker.shan.rbac.service.IPermissionService;
import org.shreker.shan.website.base.controller.WebSiteController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

@Component
public class WebsiteContextListener implements ApplicationListener<ContextRefreshedEvent> {

	@Autowired
	private IPermissionService permissionService;

	@Autowired
	private ApplicationContext applicationContext;

	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		// 找到所有打了标签的方法
		// 1> 找到所有的Controller, 2> 遍历所有的Controller中的方法, 3> 查看每个方法上是否有permissionRequired注解
		Map<String, WebSiteController> contrls = applicationContext.getBeansOfType(WebSiteController.class);
		Iterator<String> iterator = contrls.keySet().iterator();
		while (iterator.hasNext()) {
			System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
			String string = (String) iterator.next();
			WebSiteController controller = contrls.get(string);
			System.out.println(controller);
			Class<? extends WebSiteController> cls = controller.getClass();
			Method[] methods = cls.getDeclaredMethods();
			for (Method method : methods) {
				System.out.println(method);
				PermissionRequired annotation = method.getAnnotation(PermissionRequired.class);
				if (annotation != null) {
					String value = annotation.value();
					System.out.println("annotation:" + annotation);
					System.out.println("value:" + value);
					System.out.println(controller.getClass());
					System.out.println(method.getName());
					Permission permission = new Permission();
					permission.setName(value);
					String clsName = controller.getClass().getName();
					String methodName = method.getName();
					permission.setCode(clsName + "-" + methodName);
					try {
						System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
						System.out.println(permission.getCode());
						permissionService.save(permission);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}

	}

}
